package com.flong.kotlin.core.advice

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import com.flong.kotlin.utils.ObjectUtil

/**
 * 针对@RequestBody请求的处理
 */
@ControllerAdvice
@Slf4j
abstract class LiveRequestBodyAdvice : RequestBodyAdvice {

	companion object {
		var DEFAULT_CHARSET = "UTF-8";

	}

	override fun handleEmptyBody(body: Any?, inputMessage: HttpInputMessage?, parameter: MethodParameter?, targetType: Type?, converterType: Class<out HttpMessageConverter<*>>?): Any? {
		return body;
	}

	override fun afterBodyRead(body: Any?, inputMessage: HttpInputMessage?, parameter: MethodParameter?, targetType: Type?, converterType: Class<out HttpMessageConverter<*>>?): Any? {
		return body;
	}

	override fun beforeBodyRead(inputMessage: HttpInputMessage?, parameter: MethodParameter?, targetType: Type?, converterType: Class<out HttpMessageConverter<*>>?): HttpInputMessage? {
		var body = IOUtils.toString(inputMessage?.getBody(), DEFAULT_CHARSET);
		var headers = inputMessage?.getHeaders();
		//var bis 	= ByteArrayInputStream(body?.bytes(DEFAULT_CHARSET);
		var bis = ByteArrayInputStream(ObjectUtil().stringToBytes(body));

		//return InputMessage().InputMessage(headers, bis);
		return null;
	}

	override fun supports(methodParameter: MethodParameter?, targetType: Type?, converterType: Class<out HttpMessageConverter<*>>?): Boolean {
		return true;
	}


	
}

 abstract class InputMessage : HttpInputMessage {

    var  headers :HttpHeaders? =null;
    var  body : InputStream? = null;

    constructor(headers : HttpHeaders,  body : InputStream) {
      this.headers = headers;
      this.body = body;
    }
   
 
  }
	